﻿using System;
using System.Collections.Generic; 

namespace LoginServer.Net
{
    /// <summary>
    /// 消息分发
    /// </summary>
    public class MsgDisPatcher
    {
        //每帧处理消息的数量
        //private int num = 15;
        //消息列表
        private Dictionary<Type, Delegate> msgDic;
        //委托类型
        public delegate void Delegate(object[] data);
        //事件监听表
        public Queue<KeyValuePair<Type, object[]>> eventDict = new Queue<KeyValuePair<Type, object[]>>();

        public MsgDisPatcher()
        {
            msgDic = new Dictionary<Type, Delegate>();
            eventDict = new Queue<KeyValuePair<Type, object[]>>();
        }

        //Update
        public void Update()
        {
            if (eventDict.Count > 0)
            {
                KeyValuePair<Type, object[]> _event = eventDict.Dequeue();
                if (_event.Key != null && _event.Value != null)
                {
                    if (msgDic.ContainsKey(_event.Key))
                    {
                        msgDic[_event.Key](_event.Value);
                    }
                }
            }
        }

        /// <summary>
        /// 添加事件监听 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cb"></param>
        public void AddListener(Type name, Delegate cb)
        {
            if (msgDic.ContainsKey(name))
            {
                msgDic[name] += cb;
            }
            else
            {
                msgDic.Add(name, cb);
            }
        }

        public void DelListener(Type name, Delegate cb)
        {
            if (msgDic.ContainsKey(name))
            {
                msgDic[name] -= cb;
            }
            else
            {
                msgDic.Add(name, cb);
            }
        }
    }
}
